package cn.xrfzh.common.utils;

import org.jetbrains.annotations.NotNull;

import java.security.SecureRandom;

public class RandomNumberGenerator {

    public static void main(String[] args) {
        int length = 32; // 256 bits / 8 = 32 bytes
        String randomString = generateRandomString(length);
        System.out.println("Random String: " + randomString);
    }

    /**
     * 生成指定长度带符号的随机数
     *
     * @param length
     * @return
     */
    public static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-+=<>?";
        return getString(length, characters);
    }

    /**
     * 生成指定长度不带符号的随机数
     *
     * @param length
     * @return
     */
    public static String generateRandomStringWithoutSymbol(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        return getString(length, characters);
    }

    @NotNull
    private static String getString(int length, String characters) {
        SecureRandom secureRandom = new SecureRandom();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = secureRandom.nextInt(characters.length());
            sb.append(characters.charAt(randomIndex));
        }
        return sb.toString();
    }

}
